//
//  ViewController.m
//  FileStorage
//
//  Created by wanglei on 17/1/14.
//  Copyright © 2017年 wanglei. All rights reserved.
//

#import "ViewController.h"
#import "SingleVip.h"

#define K_IMG @"http://news.eastday.com/images/thumbnailimg/month_1511/201511170142052896.jpg"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
  //  [self demoOne];
   // [self demoTwo];
   // [self demoThree];
   // [self demoFour];
   // [self demoFive];
    [self demoSix];

}

/*----------------------------------沙盒路径-----------------------------------*/

-  (void)demoOne{
    
    NSString *homePath =NSHomeDirectory();
    NSLog(@"homePath = %@\n",homePath);
    
    
    //第一个参数：要查询的文件的路径
    //第二个参数：要查询路径所属的用户 iOS是单用户
    //第三个参数的意思 YES是绝对路径 NO是相对路径
    //区别于OS-X系统 iOS应用文件夹中通常只有一个文件路径 由于OC同时支持的苹果系列产品的开发 在MacOS里面会同时存在很多软件 通常生成的路径放在一个数组里面
    //iOS端一次只有一个应用 所以取数组唯一的一个元素即可
    NSArray *documentArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, NO);
    NSLog(@"documentArray = %@\n",documentArray);//打印的结果是 "~/Documents"
    NSString *documentPath = [documentArray firstObject];
    NSLog(@"documentPath = %@\n",documentPath);//结果是 ~/Documents
    
    //  对比以上我们可以打印试着获取几个路径
    NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)firstObject];
    NSLog(@"libraryPath = %@\n",libraryPath);
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject];
    NSLog(@"ChchesPath = %@\n",cachesPath);
    
    NSString *preferencePath2 =[libraryPath stringByAppendingString:@"/preferences"];
    NSLog(@"preferencePath2 = %@\n",preferencePath2);
    
}

/*----------------------------------常见的基本类型NSSTring的储存-----------------------------------*/

- (void)demoTwo{
    
    //准备字符串
    NSString *string  = @"I love my iOS teacher";
    //2 准备路径
    NSString *path =NSHomeDirectory();
    path = [path stringByAppendingString:@"/见哥.txt"];
    NSLog( @"path = %@", path);
    //3 写入文件
    //    3.1第一个参数 路径
    //    3.2第二个参数 是否进行线性操作（YES保证发生意外时有中转文件来保存信息 直至写入完成 但是损耗大. NO的时候写入速度快 但是没有安全保障）
    //    3.3第三个参数 编码方式
    //    3.4第四个参数 错误对象
    [string writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    
    //文件的读取
    NSString *contentString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"%@",contentString);

    
}


/*----------------------------------常见的基本类型NSArray的储存-----------------------------------*/

- (void)demoThree{
    
    NSArray *array = [NSArray arrayWithObjects:@"Lily",@"Yucui",@"Star",@"Ling",@"Wenqi",@"Yangyang", nil];
    NSString *docuPath =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];
    docuPath =[docuPath stringByAppendingString:@"/Lady.txt"];
    NSLog(@"docuPath = %@",docuPath);
    //写入文件
    [array writeToFile:docuPath atomically:YES];
    
    //取出文件
    NSArray *array1 = [NSArray arrayWithContentsOfFile:docuPath];
    NSLog(@"array1 = %@",array1);
    
    
}

/*----------------------------------常见的基本类型NSdata的储存-----------------------------------*/

- (void)demoFour{
    
    UIImage *image =[UIImage imageNamed:@"11.jpg"];
    NSString *homePath =NSHomeDirectory();
    homePath = [homePath stringByAppendingString:@"/Sex.jpg"];
    // compressionQuality表示压缩系数,0--1,越大越清晰
    NSData *data = UIImageJPEGRepresentation(image, 1);
    [data writeToFile:homePath atomically:YES];
    //读取图片
    UIImageView *aImageView  = [[UIImageView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    aImageView.contentMode = UIViewContentModeScaleAspectFill;
    aImageView.image = [UIImage imageWithContentsOfFile:homePath];
    [self.view addSubview:aImageView];

}

/*----------------------------------复杂对象写入的储存-----------------------------------*/
- (void)demoFive{
    
    SingleVip *man =[SingleVip new];
    man.name = @"见哥";
    man.age = 18;
    man.car = @"凤凰牌大联合";
    man.assets = @"穷类屌蛋精光";
    
        //准备路径
    NSString *homePath =NSHomeDirectory();
    homePath = [homePath stringByAppendingString:@"/钻石王老五.db"];
    NSLog(@"homePath = %@",homePath);
        //创建数据对象 用来存放vip对象
    NSMutableData *data =[NSMutableData data];
        //创建归档对象
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
        //开始归档
    [archiver encodeObject:man forKey:@"vip"];
        //完成归档
    [archiver finishEncoding];
        //写入文件
    [data writeToFile:homePath atomically:YES];
    
    
    //反归档
    //将文件里面的data对象读取出来
    NSData *_data = [NSData dataWithContentsOfFile:homePath];
    //创建反归档对象
    NSKeyedUnarchiver *unArchiver =[[NSKeyedUnarchiver alloc]initForReadingWithData:_data];
    SingleVip *_vip = [unArchiver decodeObjectForKey:@"vip"];
    [unArchiver finishDecoding];//完成反归档
    NSLog(@"%@",_vip.name);
}


- (void)demoSix{
    

    __weak typeof(self) weakSelf = self;
    
    NSURLSessionDownloadTask *downLoadTask = [[NSURLSession sharedSession]downloadTaskWithURL:[NSURL URLWithString:K_IMG] completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //data对象
        NSData *data = [NSData dataWithContentsOfURL:location];
        
        //创建文件管理者对象
        NSFileManager *fileManeger = [NSFileManager defaultManager];
        
        //文件夹路径操作
        NSString *homePath = NSHomeDirectory();
        homePath = [homePath stringByAppendingPathComponent:@"男神"];
        [fileManeger createDirectoryAtPath:homePath withIntermediateDirectories:YES attributes:nil error:nil ];
        
        homePath = [homePath stringByAppendingString:@"/god"];
        [fileManeger createFileAtPath:homePath contents:data attributes:nil];
        
//        dispatch_async(dispatch_get_main_queue(), ^{
//            
//            // /*
//            UIImage *aImage = [UIImage imageWithContentsOfFile:homePath];
//            UIImageView *aImageView = [[UIImageView alloc]initWithFrame:[UIScreen mainScreen].bounds];
//            aImageView.image = aImage;
//            [weakSelf.view addSubview:aImageView];
//            // */
//        });
       
        
        //这里以删除文件为例
        BOOL res=[fileManeger removeItemAtPath:homePath error:nil];
        if (res) {
            NSLog(@"文件删除成功");
        }else
            NSLog(@"文件删除失败");
        NSLog(@"文件是否存在: %@",[fileManeger isExecutableFileAtPath:homePath]?@"YES":@"NO");
            
    }
];
    
    
    [downLoadTask resume];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
